package cn.tedu.boot21.controller;

import cn.tedu.boot21.entity.User;
import cn.tedu.boot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author wxd
 * @version 1.0
 */
@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user) {
        // 得到数据库链接
        try (
                Connection conn = DBUtils.getConn()
        ) {
            String sql1 = "select id from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql1);
            ps.setString(1, user.getUsername());
            ResultSet res = ps.executeQuery();
            if (res.next()) {
                return "用户名已存在";
            }
            String sql = "insert into user values(null,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "注册成功";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String log(User user) {
        // soutp可以快速的在控制台输出参数
        System.out.println("user = " + user);
        try (
                Connection conn = DBUtils.getConn()
        ) {
            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ResultSet res = ps.executeQuery();
            if (res.next()) {
                String psw = res.getString(1);
                if (psw.equals(user.getPassword())) {
                    return "登录成功!";
                }
                return "密码不正确,请重新输入!";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "用户不存在,请输入正确的用户名!";
    }
}
